/**
 * 添加缺失物品脚本
 * 功能：将缺失的"跌打药"添加到数据库中
 */

const mysql = require('mysql2/promise');

// 数据库连接配置（硬编码）
const DB_CONFIG = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

class MissingItemAdder {
    constructor() {
        this.connection = null;
    }

    // 连接数据库
    async connectDatabase() {
        try {
            console.log('🔌 正在连接数据库...');
            this.connection = await mysql.createConnection(DB_CONFIG);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async closeDatabase() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 添加缺失的"跌打药"
    async addMissingItem() {
        try {
            console.log('🔍 检查ID为1的位置...');

            // 检查ID为1是否已存在
            const [existing] = await this.connection.execute(
                'SELECT id, name FROM basic_items WHERE id = 1'
            );

            if (existing.length > 0) {
                console.log(`⚠️  ID 1 已被物品 "${existing[0].name}" 占用`);
                return false;
            }

            console.log('✅ ID 1 位置为空，可以添加物品');

            // 添加"跌打药"
            const itemData = {
                id: 1,
                name: '跌打药',
                gold_price: 0,
                silver_price: 50,
                lv: 1,
                weight: 1,
                description: '散瘀消肿，强筋健骨，可迅速补充气血。',
                pic: '',
                is_treasure_shop: 0,
                is_exp_shop: 0,
                status: 1
            };

            console.log('📝 正在添加"跌打药"...');

            await this.connection.execute(`
                INSERT INTO basic_items (
                    id, name, gold_price, silver_price, lv, weight, 
                    description, pic, is_treasure_shop, is_exp_shop, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `, [
                itemData.id,
                itemData.name,
                itemData.gold_price,
                itemData.silver_price,
                itemData.lv,
                itemData.weight,
                itemData.description,
                itemData.pic,
                itemData.is_treasure_shop,
                itemData.is_exp_shop,
                itemData.status
            ]);

            console.log('✅ "跌打药"添加成功！');

            // 验证添加结果
            const [added] = await this.connection.execute(
                'SELECT id, name, silver_price, lv, weight, description FROM basic_items WHERE id = 1'
            );

            if (added.length > 0) {
                console.log('\n📊 添加的物品详情:');
                console.log(`   ID: ${added[0].id}`);
                console.log(`   名称: ${added[0].name}`);
                console.log(`   银两价格: ${added[0].silver_price}`);
                console.log(`   等级: ${added[0].lv}`);
                console.log(`   负重: ${added[0].weight}`);
                console.log(`   描述: ${added[0].description}`);
            }

            return true;

        } catch (error) {
            console.error('❌ 添加物品失败:', error.message);
            return false;
        }
    }

    // 验证总数
    async verifyCount() {
        try {
            const [count] = await this.connection.execute(
                'SELECT COUNT(*) as total FROM basic_items'
            );

            console.log(`\n📊 数据库物品总数: ${count[0].total}`);
            return count[0].total;

        } catch (error) {
            console.error('❌ 验证总数失败:', error.message);
            return 0;
        }
    }

    // 运行添加流程
    async runAdd() {
        console.log('🚀 开始添加缺失物品...\n');

        try {
            // 1. 连接数据库
            await this.connectDatabase();

            // 2. 添加缺失物品
            const success = await this.addMissingItem();

            if (success) {
                // 3. 验证总数
                await this.verifyCount();
                console.log('\n🎉 缺失物品添加完成！');
            } else {
                console.log('\n⚠️  添加失败或物品已存在');
            }

        } catch (error) {
            console.error('💥 添加流程失败:', error.message);
            throw error;
        } finally {
            // 4. 关闭数据库连接
            await this.closeDatabase();
        }
    }
}

// 运行添加
async function main() {
    console.log('🎯 缺失物品添加工具');
    console.log('   目标：添加缺失的"跌打药"到数据库\n');

    const adder = new MissingItemAdder();
    await adder.runAdd();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = MissingItemAdder;
